/*
 * (c) Copyright 2014 Hewlett-Packard Development Company, L.P. All rights reserved.
 */
package com.hp.snap.gr.cmd;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.snap.gr.utils.Constants;
import com.hp.snap.gr.utils.eium.JMXClientUtils;

/**
 * @since 3.2
 * @author Yang, Lin
 * 
 */
public class GetSessionServerStatusCMD {
    private static Logger logger = LoggerFactory.getLogger(GetSessionServerStatusCMD.class);

    /**
     * <b>input</b>
     * <p>
     * args[0]: JSON refer to gr-manager/src/main/artifacts/session_server/snap-status.sh
     * 
     * <pre>
     * {"results":[{"session_server":"STUDIO/snap460c03.chn.hp.com/SNAPStudio1","state":"Running"},{"session_server":"STUDIO/snap460c06.chn.hp.com/SNAPStudio2","state":"Stopped"}]}
     * </pre>
     * 
     * <b>output</b>
     * <p>
     * Constants.CONSOLE.info() add server_status and biz_service_status for each session server
     * 
     * <pre>
     * {"results":[{"session_server":"STUDIO/snap460c03.chn.hp.com/SNAPStudio1","state":"Running","server_status":"ACTIVE","biz_service_status":"Standby"},{"session_server":"STUDIO/snap460c06.chn.hp.com/SNAPStudio2","state":"Stopped"}]}
     * </pre>
     * 
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) {
        try {
            String output = main0(new JSONObject(args[0]));

            // output
            Constants.CONSOLE.info(output);
        } catch (Exception e) {
            if (logger.isTraceEnabled()) {
                logger.trace("Get session server status is failed!", e);
            }

            // output
            Constants.CONSOLE.info(args[0]);
            System.exit(1);
        } finally {
            try {
                JMXClientUtils.destroy();
            } catch (Exception e) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Destroying JMX connection is failed!", e);
                }
            }
        }
    }

    private static String main0(JSONObject input) throws Exception {
        JSONArray results = input.getJSONArray("results");
        if (results.length() < 1) {
            return input.toString();
        }

        for (int ii = 0, nn = results.length(); ii < nn; ii++) {
            JSONObject ssRow = results.getJSONObject(ii);

            String session_server = ssRow.getString("session_server");
            String state = ssRow.getString("state");

            if (!"Running".equalsIgnoreCase(state)) {
                continue;
            }

            // get server_status and biz_service_status for each session server

            String[] session_server_split = StringUtils.split(session_server, "/");
            String hostname = session_server_split[1];
            String session_server_name = session_server_split[2];

            // server_status
            String mbean_server_status = new StringBuilder().append(hostname).append("/").append(session_server_name)
                    .append("/").append("ATOM:type=Server,name=ATOM Server").toString();
            String attribute_server_status = "Status";

            try {
                Object server_status = JMXClientUtils.getAttribute(mbean_server_status, attribute_server_status);
                ssRow.put("server_status", String.valueOf(server_status));
            } catch (Exception e) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Get attribute " + attribute_server_status + " from " + mbean_server_status
                            + " is failed!", e);
                }
                ssRow.put("server_status", "IDLE");
            }

            // biz_service_status
            String mbean_biz_service_status = new StringBuilder().append(hostname).append("/")
                    .append(session_server_name).append("/").append(Constants.JMX_SNAP_OBJECT).toString();

            try {
                Object biz_service_status = JMXClientUtils.invokeOperation(mbean_biz_service_status,
                        Constants.JMX_GET_BIZ_STATUS, null, null);
                ssRow.put("biz_service_status", String.valueOf(biz_service_status));
            } catch (Exception e) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Invoke operation " + Constants.JMX_GET_BIZ_STATUS + " from "
                            + mbean_biz_service_status + " is failed!", e);
                }
                ssRow.put("biz_service_status", "IDLE");
            }
        }

        return input.toString();
    }
}
